import React, { useRef, useEffect, useState } from 'react';
import { useReactFlow, useStore } from 'reactflow';

interface Props {
  width?: number;
  height?: number;
}

export default function InteractiveMiniMap({ width = 200, height = 120 }: Props) {
  const { setViewport, getViewport } = useReactFlow();
  const rfBounds = useStore((s) => s.transform);
  const svgRef = useRef<SVGSVGElement>(null);

  const [dragging, setDragging] = useState(false);
  const [dragStart, setDragStart] = useState({ x: 0, y: 0 });

  /* ---- 计算视口在缩略图中的位置 ---- */
  const scale = Math.min(width / rfBounds.width, height / rfBounds.height);
  const viewX = -rfBounds.x * scale;
  const viewY = -rfBounds.y * scale;
  const viewW = (window.innerWidth / rfBounds.zoom) * scale;
  const viewH = (window.innerHeight / rfBounds.zoom) * scale;

  /* 鼠标 → 视口坐标 */
  const clientToPoint = (e: React.MouseEvent) => {
    if (!svgRef.current) return { x: 0, y: 0 };
    const rect = svgRef.current.getBoundingClientRect();
    return {
      x: (e.clientX - rect.left) / scale,
      y: (e.clientY - rect.top) / scale,
    };
  };

  const handleMouseDown = (e: React.MouseEvent) => {
    e.preventDefault();
    setDragging(true);
    setDragStart(clientToPoint(e));
  };

  const handleMouseMove = (e: React.MouseEvent) => {
    if (!dragging) return;
    const pt = clientToPoint(e);
    const dx = pt.x - dragStart.x;
    const dy = pt.y - dragStart.y;
    setViewport({ x: -dx, y: -dy, zoom: getViewport().zoom });
  };

  const handleMouseUp = () => setDragging(false);

  return (
    <svg
      ref={svgRef}
      width={width}
      height={height}
      className="interactive-minimap"
      style={{
        position: 'absolute',
        bottom: 10,
        right: 10,
        border: '1px solid #ccc',
        background: '#fff',
        cursor: dragging ? 'grabbing' : 'grab',
        zIndex: 10,
      }}
      onMouseDown={handleMouseDown}
      onMouseMove={handleMouseMove}
      onMouseUp={handleMouseUp}
      onMouseLeave={handleMouseUp}
    >
      {/* 所有节点的小圆点 */}
      {Array.from({ length: 100 }).map((_, i) => (
        <circle
          key={i}
          cx={10 + (i % 10) * 18}
          cy={10 + Math.floor(i / 10) * 10}
          r={2}
          fill="#999"
        />
      ))}

      {/* 红色视口矩形 */}
      <rect
        x={viewX}
        y={viewY}
        width={viewW}
        height={viewH}
        fill="rgba(255,85,85,0.6)"
        stroke="#ff5555"
        strokeWidth={1}
      />
    </svg>
  );
}